<?php

namespace api\modules\backend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use common\library\traits\APITrait;
use common\commands\Common;

/**
 * User model
 *
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    use APITrait;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%role}}';
    }


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            ['active', 'default', 'value' => self::STATUS_ACTIVE],
            ['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function response($data)
    {
        header('Content-Type: application/json; charset=' . Yii::$app->charset);
        exit(json_encode($data));
    }

    /**
     * findIdentityByAccessToken - 令牌查询
     * @param mixed $token
     * @param null $type
     * @return null|void|IdentityInterface|static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 如果token无效的话，
        if (!static::apiTokenIsValid($token)) {
            return static::response(Common::getPackedResponse(TOKEN_FAILED, 'TOKEN_FAILED'));
            // throw new \yii\web\UnauthorizedHttpException("token is invalid.");
        }

        return static::findOne(['access_token' => $token, 'active' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * apiTokenIsValid - 令牌验证
     * @param $token
     * @return bool
     */
    public static function apiTokenIsValid($token)
    {

        if (empty($token)) {//如果token为空
            return false;
        }
        $user = static::findOne(['access_token' => $token, 'active' => self::STATUS_ACTIVE]);//获取当前登录人信息
        if (empty($user)) {
            return false;
        }
        $apiTokenExpire = $user->access_token_expire;//将过期时间时间戳化
        $expire = Yii::$app->params['role.apiTokenExpire'];

        if ($apiTokenExpire < time()) {//判断是否过期，如果过期时间戳小于当前时间戳  则为已经过期   如果过期时间戳大于当前时间戳则代表token还有效
            return false;
        } else {
            $newApiTokenExpire = time() + $expire;//新的过期时间
            $user->access_token_expire = $newApiTokenExpire;
            $user->last_ip = Yii::$app->request->getUserIP();
            $user->save();

            return true;
        }

    }
}
